package org.spring.file.mapped;

import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author chengzhengzheng
 * @date 2019/11/1
 **/
public class TestMain {
	public static void main(String[] args) throws IOException {
		ClassLoader classLoader = TestMain.class.getClassLoader();
		Path path = Paths.get(classLoader.getResource("test.txt").getPath());
		CharBuffer buffer = null;
		FileChannel channel = FileChannel.open(path);
		MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
		if (mappedByteBuffer != null) {
			buffer = Charset.forName("UTF-8").decode(mappedByteBuffer);
		}
		System.out.println(buffer.toString());

		channel = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
		mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024);

		CharBuffer charBuffer = CharBuffer.wrap("沉默王二，《Web全栈开发进阶之路》作者");
		path = Paths.get(classLoader.getResource("test2.txt").getPath());

		try (FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE,
				StandardOpenOption.TRUNCATE_EXISTING)) {
			mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 1024);

			if (mappedByteBuffer != null) {
				mappedByteBuffer.put(Charset.forName("UTF-8").encode(charBuffer));
			}

		} catch (IOException e) {
			e.printStackTrace();
		}


	}
}
